#include "changepassworddialog.h"
#include "ui_changepassworddialog.h"
#include <QDebug>

ChangePasswordDialog::ChangePasswordDialog(const UserInfo &userInfo, QWidget *parent)
    : QDialog(parent), ui(new Ui::ChangePasswordDialog), m_userInfo(userInfo)
{
    ui->setupUi(this);

    // 设置窗口属性
    setFixedSize(400, 300);
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);

    // 连接信号槽
    connect(ui->confirmBtn, &QPushButton::clicked, this, &ChangePasswordDialog::onConfirmClicked);
    connect(ui->cancelBtn, &QPushButton::clicked, this, &ChangePasswordDialog::onCancelClicked);

    // 监听密码输入框变化
    connect(ui->currentPasswordEdit, &QLineEdit::textChanged, this, &ChangePasswordDialog::onPasswordTextChanged);
    connect(ui->newPasswordEdit, &QLineEdit::textChanged, this, &ChangePasswordDialog::onPasswordTextChanged);
    connect(ui->confirmPasswordEdit, &QLineEdit::textChanged, this, &ChangePasswordDialog::onPasswordTextChanged);

    // 设置焦点到当前密码输入框
    ui->currentPasswordEdit->setFocus();

    // 初始化界面状态
    updateUI();
}

ChangePasswordDialog::~ChangePasswordDialog()
{
    delete ui;
}

void ChangePasswordDialog::onConfirmClicked()
{
    QString currentPassword = ui->currentPasswordEdit->text().trimmed();
    QString newPassword = ui->newPasswordEdit->text().trimmed();
    QString confirmPassword = ui->confirmPasswordEdit->text().trimmed();

    // 验证当前密码
    if (!validateCurrentPassword(currentPassword))
    {
        QMessageBox::warning(this, "错误", "当前密码不正确！");
        ui->currentPasswordEdit->setFocus();
        return;
    }

    // 验证新密码
    if (!validateNewPassword(newPassword))
    {
        QMessageBox::warning(this, "错误", "新密码格式不符合要求！\n密码长度至少6位。");
        ui->newPasswordEdit->setFocus();
        return;
    }

    // 验证两次新密码是否一致
    if (newPassword != confirmPassword)
    {
        QMessageBox::warning(this, "错误", "两次输入的新密码不一致！");
        ui->confirmPasswordEdit->setFocus();
        return;
    }

    // 检查新密码是否与当前密码相同
    if (currentPassword == newPassword)
    {
        QMessageBox::warning(this, "错误", "新密码不能与当前密码相同！");
        ui->newPasswordEdit->setFocus();
        return;
    }

    // 更新密码到数据库
    if (updatePassword(newPassword))
    {
        QMessageBox::information(this, "成功", "密码修改成功！请重新登录。");
        emit passwordChangedSuccessfully();
        accept(); // 关闭对话框并返回 QDialog::Accepted
    }
    else
    {
        QMessageBox::critical(this, "错误", "密码修改失败，请稍后重试！");
    }
}

void ChangePasswordDialog::onCancelClicked()
{
    reject(); // 关闭对话框并返回 QDialog::Rejected
}

void ChangePasswordDialog::onPasswordTextChanged()
{
    updateUI();
}

bool ChangePasswordDialog::validateCurrentPassword(const QString &password)
{
    if (password.isEmpty())
    {
        return false;
    }

    DatabaseManager &dbManager = DatabaseManager::getInstance();

    // 查询数据库验证当前密码
    QSqlQuery query(dbManager.getDatabase());
    query.prepare("SELECT password FROM users WHERE id = ?");
    query.addBindValue(m_userInfo.id);

    if (query.exec() && query.next())
    {
        QString storedPassword = query.value("password").toString();
        return storedPassword == password;
    }

    return false;
}

bool ChangePasswordDialog::validateNewPassword(const QString &password)
{
    // 密码长度至少6位
    if (password.length() < 6)
    {
        return false;
    }

    // 可以在这里添加更多的密码强度验证
    // 例如：必须包含字母和数字等

    return true;
}

bool ChangePasswordDialog::updatePassword(const QString &newPassword)
{
    DatabaseManager &dbManager = DatabaseManager::getInstance();

    // 更新数据库中的密码
    QSqlQuery query(dbManager.getDatabase());
    query.prepare("UPDATE users SET password = ? WHERE id = ?");
    query.addBindValue(newPassword);
    query.addBindValue(m_userInfo.id);

    if (!query.exec())
    {
        qDebug() << "密码更新失败:" << query.lastError().text();
        return false;
    }

    // 记录操作日志（可以通过添加库存记录来记录此操作）
    // QString logMessage = QString("用户 %1 修改了密码").arg(m_userInfo.username);
    // 注意：DatabaseManager中没有addOperationLog方法，此处暂时注释

    return true;
}

void ChangePasswordDialog::updateUI()
{
    QString currentPassword = ui->currentPasswordEdit->text().trimmed();
    QString newPassword = ui->newPasswordEdit->text().trimmed();
    QString confirmPassword = ui->confirmPasswordEdit->text().trimmed();

    // 只有当所有字段都不为空时才启用确认按钮
    bool enableConfirm = !currentPassword.isEmpty() &&
                         !newPassword.isEmpty() &&
                         !confirmPassword.isEmpty();

    ui->confirmBtn->setEnabled(enableConfirm);
}
